package com.zf.shuashua.ui.mine;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;

import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.BR;
import com.zf.shuashua.helper.LoadDialogManager;
import com.zf.shuashua.R;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BaseViewModel;
import com.zf.shuashua.base.BasicActivity;
import com.zf.shuashua.bean.LoginBean;
import com.zf.shuashua.bean.VerifyCode;
import com.zf.shuashua.databinding.ActivityVerifyThirdBinding;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.utils.TextUtil;
import com.zf.shuashua.utils.ToastUtil;

public class VerifyThirdActivity extends BasicActivity<ActivityVerifyThirdBinding, BaseViewModel> {

    private String phoneNumber;
    private MyCountDownTimer myCountDownTimer;

    @Override
    public int getLayoutId() {
        return R.layout.activity_verify_third;
    }

    @Override
    public int getViewModelId() {
        return BR.viewModel;
    }

    @Override
    public BaseViewModel getViewModel() {
        return ViewModelProviders.of(this).get(BaseViewModel.class);
    }

    @Override
    public void setupView() {
        binding.imgBack.setOnClickListener(v -> {
            finish();
        });
        binding.tvtoProtocol.setOnClickListener(v -> {
            jumpToProtocol();
        });
        binding.tvtoPolicy.setOnClickListener(v -> {
            jumpToPolicy();
        });
        binding.tvAgain.setOnClickListener(v -> {
            getVerifyCode();
        });
        binding.login.setOnClickListener(v -> {
            login();
        });
        setupVerifyCode();
    }

    @Override
    public void initData() {
        super.initData();
        String name = getIntent().getStringExtra("name");
        binding.tvName.setText(name);

        String avatar = getIntent().getStringExtra("iconUrl");
        Glide.with(this).load(avatar)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))//圆形
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(binding.imgAvatar);

        myCountDownTimer = new MyCountDownTimer(60000, 1000);
        phoneNumber = getIntent().getStringExtra("phoneNumber");
        if (TextUtil.isMobile(phoneNumber)) {
            binding.tvTips.setText(String.format(getResources().getString(R.string.send_code), phoneNumber));
            getVerifyCode();
        } else {
            ToastUtil.show(this, "手机号有误");
        }
    }

    private void setupVerifyCode(){
        binding.etVerifyCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s) && s.length() == 5) {
                    binding.login.setEnabled(true);
                } else {
                    binding.login.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoadDialogManager.getInstance().dismiss();
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
            myCountDownTimer = null;
        }
    }

    //倒计时函数
    private class MyCountDownTimer extends CountDownTimer {


        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            binding.tvAgain.setClickable(false);
            binding.tvAgain.setText("重新获取(" + l / 1000 + "秒)");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            binding.tvAgain.setText("重新获取");
            //设置可点击
            binding.tvAgain.setClickable(true);
        }
    }

    private void login(){
        String smsCode = binding.etVerifyCode.getText().toString();
        if (TextUtils.isEmpty(smsCode)) {
            ToastUtil.showToast(VerifyThirdActivity.this, "请填写正确的验证码");
            return;
        }
        userLogin(smsCode);
    }

    private void getVerifyCode() {
        HttpData.getInstance().getVerifyCode(phoneNumber, new ACallback<VerifyCode>() {
            @Override
            public void onSuccess(VerifyCode data) {
                if (data.isSuccess()) {
                    myCountDownTimer.start();
                    if (data.getMessage() != null) {
                        ToastUtil.showToast(VerifyThirdActivity.this, data.getMessage());
                    }
                } else {
                    if (data.getMessage() != null) {
                        ToastUtil.showToast(VerifyThirdActivity.this, data.getMessage());
                    }

                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });
    }

    private void userLogin(String smsCode) {
        LoadDialogManager.getInstance().show(this);
        HttpData.getInstance().login(phoneNumber, smsCode, new ACallback<LoginBean>() {
            @Override
            public void onSuccess(LoginBean data) {
                LoadDialogManager.getInstance().dismiss();
                if (data != null && data.getData() != null) {
                    Store.getInstance().setIsNewUser(data.getData().isIs_new_user());//新人
                    Store.getInstance().loginSuccess(VerifyThirdActivity.this, data.getData().getToken_type(), data.getData().getAccess_token(), data.getData(), "ZH");
                    finish();
                } else {
                    ToastUtil.showToast(VerifyThirdActivity.this, data.getMessage() + "");
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                LoadDialogManager.getInstance().dismiss();
                ToastUtil.showToast(VerifyThirdActivity.this, "登录失败,请重试");
            }
        });
    }

    private void jumpToProtocol(){
        Intent intent = new Intent(this, H5Activity.class);
        intent.putExtra("money", Constants.H5_URL + "protocol");
        intent.putExtra("title", "长豆用户协议");
        startActivity(intent);
    }

    private void jumpToPolicy(){
        Intent intent = new Intent(this, H5Activity.class);
        intent.putExtra("money", Constants.H5_URL + "policy");
        intent.putExtra("title", "长豆隐私政策");
        startActivity(intent);
    }
}
